import { Request, Response, Router } from 'express'
import sqlQuery from '../mysql'
import { createUserTabelSql, queryUserPhoneExistence, updateUserNickName, register } from '../sql/login'

const router: Router = Router()

router.post('/login', async (req: Request, res: Response) => {
  try {
    const { userPhone, password, nickName } = req.body

    await createUserTableIfNotExists()

    // 查询表中是否有对应的手机号
    const user = await findUserByPhone(userPhone);

    if (user) {
      // 有对应的手机号走登录流程
      await handleLogin(user, password, nickName, res);
    } else {
      // 走注册流程
      await handleRegister(nickName, userPhone, password, res);
    }
  } catch (error) {
    res.send({
      code: 0,
      message: '请求失败',
      result: error
    })
  }
})

async function createUserTableIfNotExists() {
  await sqlQuery(createUserTabelSql);
}

async function findUserByPhone(userPhone: string) {
  const result = await sqlQuery(queryUserPhoneExistence(userPhone));
  // 如果有数据则返回数据
  return result.length ? result[0] : null;
}

async function handleLogin(
  user: { userPhone: string; password: string; nickName: string },
  password: string,
  nickName: string,
  res: Response
) {
  // 密码正确则代表登录成功
  if (user.password === password) {
    // 更新新的用户名称
    if (nickName !== user.nickName) {
      await sqlQuery(updateUserNickName(nickName, user.userPhone));
    }
    res.send({
      code: 200,
      message: '登录成功',
      result: { userPhone: user.userPhone, nickName }
    });
  } else {
    // 密码失败的返回
    res.send({ code: 401, message: '密码错误' });
  }
}

async function handleRegister(
  nickName: string,
  userPhone: string,
  password: string,
  res: Response
) {
  await sqlQuery(register(nickName, userPhone, password));
  res.send({
    code: 200,
    message: '注册并登录成功',
    result: { userPhone, nickName }
  });
}

export default router
